
const getAuth = require('./api/apiGetAuth')
const RxFileWrite = require('rxfile-write')

const pathResolve = require('path').join
const RootPath = pathResolve(__dirname, '/data/auth.json')

let timer = null

function _createTimer(cb) {
  _destoryTimer()
  timer = setTimeout(() => {
    cb && cb()
  }, 3000);
}

function _destoryTimer() {
  if (timer) {
    clearTimeout(timer)
  }
  timer = null
}

function updateDevices(devices, ip, port) {
  return new Promise((resolve, reject) => {
    _createTimer(() => {
      if (!(devices && Array.isArray(devices))) {
        reject()
        return
      }
      let authFailDev = null
      let authDevice = null
      for (let i = 0; i < devices.length; i ++) {
        const device = devices[i]
        const deviceid = device.deviceid
        const auth = device.auth || false
        if (auth) {
          authDevice = device
          authFailDev = deviceid
          reject()
          break
        }
      }

      if (authFailDev) {
        const ds= [authFailDev]
        console.log('ds=',ds)
        const date = Math.floor(Date.now() / 1000)
        const valid = 3600
        getAuth(ds, date, valid).then(data => {
          console.log('获取身份验证成功 auth=', data)
          data = data || {}
          const status = data.status || 0
          if (status == 200) {
            const auth = data.auth
            if (auth) {
              data.device = authDevice
              data.date = date
              data.valid = valid
              data.server = {ip, port}
              const writeData = JSON.stringify(data)
              RxFileWrite.writeSync(RootPath, writeData)
              resolve()
            } else {
              reject('请求服务器 auth 不见了')
            }
          } else reject('请求状态不是 200')
        }).catch(() => {
          reject('请求 参数不对')
        })
      } else reject('没有获取到，auth=false的设备,不进行联调')
    })
  })
}

module.exports = {updateDevices}